package com.kyxx.topics.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.OnTextChangeAdapter;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.CircleImageView;
import com.kyxx.topics.view.UIDialog;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class CustomMemberActivity extends BaseActivity {
    @Bind(R.id.iv_back)
    ImageView iv_back;
    @Bind(R.id.tv_baocun)
    TextView tv_baocun;
    @Bind(R.id.rl_join_bar)
    RelativeLayout rl_join_bar;
    @Bind(R.id.et_join_member_num)
    EditText et_join_member_num;
    @Bind(R.id.ll_member_card_num)
    LinearLayout ll_member_card_num;
    @Bind(R.id.et_join_member_name)
    EditText et_join_member_name;
    @Bind(R.id.et_join_member_phone)
    EditText et_join_member_phone;
    @Bind(R.id.ll_member_phone)
    LinearLayout ll_member_phone;
    @Bind(R.id.tv_change_type)
    TextView tv_change_type;
    @Bind(R.id.tv_member_shop_name)
    EditText tv_member_shop_name;
    @Bind(R.id.rl_take_photo)
    RelativeLayout rl_take_photo;
    @Bind(R.id.cv_custom_member)
    CircleImageView cv_custom_member;
    private String IDcard = "";
    private String cartid = "";
    private String mobile = "";
    private String name = "";
    private String shop_name = "";
    private boolean isCardType = true;
    private File f;

    protected void findViewById() {
    }

    protected void loadViewLayout() {
        setContentView(R.layout.activity_custom_member);
        ButterKnife.bind(this);
    }


    protected void processLogic() {
        tv_change_type.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tv_change_type.getPaint().setAntiAlias(true);//抗锯齿
    }

    protected void setListener() {
        et_join_member_num.addTextChangedListener(new OnTextChangeAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                cartid = et_join_member_num.getText().toString().trim();
            }
        });
        et_join_member_name.addTextChangedListener(new OnTextChangeAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                name = et_join_member_name.getText().toString().trim();
            }
        });
        et_join_member_phone.addTextChangedListener(new OnTextChangeAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                mobile = et_join_member_phone.getText().toString().trim();
            }
        });
        tv_member_shop_name.addTextChangedListener(new OnTextChangeAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                shop_name = tv_member_shop_name.getText().toString().trim();
            }
        });
    }

    private void regist() {
        RequestParams params = new RequestParams();
        JSONObject obj = new JSONObject();
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("shop_name", shop_name);
        obj.put("cardnum", cartid);
        obj.put("name", name);
        obj.put("IDcard", IDcard);
        obj.put("mobile", mobile);
        params.put("json", obj.toString());
        try {
            params.put("logo",f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        RestClient.post(UrlUtils.CUSTOM_CARD, params, context, new ResponseListener(this, true) {
            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject result) {
                Tools.toast(context, "添加会员卡成功");
//                startActivity(new Intent(context, MemberDeatailActivity.class).putExtra("type_id", type_id));
                finish();

            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                try {
                    if (result.getInt("code") == 1) {
                        ToastUtils.show(CustomMemberActivity.this, result.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @OnClick({R.id.iv_back, R.id.tv_baocun, R.id.tv_change_type, R.id.iv_join_member_scan, R.id.rl_take_photo,R.id.cv_custom_member})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                this.finish();
                break;
            case R.id.tv_baocun:
                if (mobile.length() > 0) {
                    if (!StringUtil.isMobileExact(mobile)) {
                        ToastUtils.show(context, "请输入正确的手机号");
                        et_join_member_phone.setText("");
                        return;
                    }
                }
                if (StringUtil.isEmpty(shop_name)) {
                    ToastUtils.show(context, "请输入品牌名称");
                    return;
                }
                if (StringUtil.isEmpty(cartid)) {
                    ToastUtils.show(context, "请输入卡号");
                    return;
                }
                regist();
                break;
            case R.id.tv_change_type:
                if (isCardType) {
                    if(StringUtil.isEmpty(tv_member_shop_name.getText().toString())){
                        ToastUtils.show(context, "请输入品牌名称");
                        return;
                    }
                    ll_member_card_num.setVisibility(View.GONE);
                    ll_member_phone.setVisibility(View.VISIBLE);
                    tv_change_type.setText("返回输入卡号");
                    isCardType = false;
                } else {
                    ll_member_card_num.setVisibility(View.VISIBLE);
                    ll_member_phone.setVisibility(View.GONE);
                    tv_change_type.setText("忘记卡号？输手机号");
                    isCardType = true;
                }
                break;
            case R.id.iv_join_member_scan:
                startActivityForResult(new Intent(this, CommonScanActivity.class), 1);
                break;
            case R.id.rl_take_photo:
                UIDialog.ForThreeBtn(this, new String[]{"拍照", "从相册选择", "取消"}, listener);
                break;
            case R.id.cv_custom_member:
                UIDialog.ForThreeBtn(this, new String[]{"拍照", "从相册选择", "取消"}, listener);
                break;
        }
    }

    private String timeString;
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.dialog_modif_1:
                      /* 拍照 */
                    UIDialog.closeDialog();
                    Date date = new Date(System.currentTimeMillis());
                    SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMddHHmmss", new Locale("zh", "CN"));
                    timeString = dateFormat.format(date);
                    createSDCardDir();
                    Intent shootIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    shootIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
                            new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera", timeString + ".jpg")));
                    startActivityForResult(shootIntent, 3);
                    break;
                case R.id.dialog_modif_2:
                    UIDialog.closeDialog();
                   /* 从相册中选取 */
                    Intent photoIntent = new Intent(Intent.ACTION_PICK, null);
                    photoIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(photoIntent, 2);
                    break;
                case R.id.dialog_modif_3://取消
                    UIDialog.closeDialog();
            }
        }
    };
    public void createSDCardDir() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // 创建一个文件夹对象，赋值为外部存储器的目录
            File sdcardDir = Environment.getExternalStorageDirectory();
            // 得到一个路径，内容是sdcard的文件夹路径和名字
            String path = sdcardDir.getPath() + "/DCIM/Camera";
            File path1 = new File(path);
            if (!path1.exists()) {
                // 若不存在，创建目录，可以在应用启动的时候创建
                path1.mkdirs();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if(data !=null){
                    et_join_member_num.setText(data.getExtras().getString("result"));
                }
                break;
            case 2:
            /* 如果是直接从相册获取 */
                try {
                    startPhotoZoom(data.getData());
                } catch (Exception e) {
                    Toast.makeText(this, "您没有选择任何照片", Toast.LENGTH_LONG).show();
                }
                break;
            case 3:
            /* 如果是调用相机拍照，图片设置名字和路径 */
                File temp = new File(
                        Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + timeString + ".jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            case 4:
            /* 取得裁剪后的图片 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            // Drawable drawable = new BitmapDrawable(photo);
            /* 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似 */
            savaBitmap(photo);
            // avatar_head_image.setBackgroundDrawable(drawable);
        }
    }
    /**
     * 将剪切后的图片保存到本地图片上！
     */
    public void savaBitmap(Bitmap bitmap) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMddHHmmss", new Locale("zh", "CN"));
        String cutnameString = dateFormat.format(date);
        String filename = Environment.getExternalStorageDirectory().getPath() + "/" + cutnameString + ".jpg";
        f = new File(filename);
        FileOutputStream fOut = null;
        try {
            f.createNewFile();
            fOut = new FileOutputStream(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);// 把Bitmap对象解析成流
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        cv_custom_member.setImageBitmap(bitmap);
        rl_take_photo.setVisibility(View.GONE);
        cv_custom_member.setVisibility(View.VISIBLE);
    }
    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 60);
        intent.putExtra("outputY", 60);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 4);
    }

}